<template>
  <div>
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class-name="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :label-width="formInfo.labelWidth"
            :rules="formInfo.rules"
          >
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>营业执照</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class-name="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="certificateOfBusinessInfo.ref"
            :data="certificateOfBusinessInfo.data"
            :field-list="certificateOfBusinessInfo.fieldList"
            :label-width="certificateOfBusinessInfo.labelWidth"
            :rules="certificateOfBusinessInfo.rules"
          >
            <template v-slot:form-licenseFilePath>
              <div class="slot-licenseFilePath">
                <upload-img
                  v-model:value="
                    certificateOfBusinessInfo.data.licenseFilePaths
                  "
                  multiple
                  :action="action"
                  title="营业执照"
                  :response-fn="handleResponse"
                />
              </div>
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>经营许可证</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class-name="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="businessLicenseInfo.ref"
            :data="businessLicenseInfo.data"
            :field-list="businessLicenseInfo.fieldList"
            :label-width="businessLicenseInfo.labelWidth"
            :rules="businessLicenseInfo.rules"
          >
            <template v-slot:form-licenseFilePath>
              <div class="slot-licenseFilePath">
                <upload-img
                  v-model:value="businessLicenseInfo.data.licenseFilePaths"
                  multiple
                  :action="action"
                  title="经营许可证"
                  :response-fn="handleResponse"
                />
              </div>
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>税务许可证</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class-name="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="taxPermit.ref"
            :data="taxPermit.data"
            :field-list="taxPermit.fieldList"
            :label-width="taxPermit.labelWidth"
            :rules="taxPermit.rules"
          >
            <template v-slot:form-licenseFilePath>
              <div class="slot-licenseFilePath">
                <upload-img
                  v-model:value="taxPermit.data.licenseFilePaths"
                  multiple
                  :action="action"
                  title="税务许可证"
                  :response-fn="handleResponse"
                />
              </div>
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>第二医疗器械经营备案证</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class-name="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="businessRecordCertificate.ref"
            :data="businessRecordCertificate.data"
            :field-list="businessRecordCertificate.fieldList"
            :label-width="businessRecordCertificate.labelWidth"
            :rules="businessRecordCertificate.rules"
          >
            <template v-slot:form-licenseFilePath>
              <div class="slot-licenseFilePath">
                <upload-img
                  v-model:value="
                    businessRecordCertificate.data.licenseFilePaths
                  "
                  multiple
                  :action="action"
                  title="第二医疗器械经营备案证"
                  :response-fn="handleResponse"
                />
              </div>
            </template>
          </page-form>
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="modifyOrgInfo">
import { getOrgInformation, updateOrgInformation } from '@/api/core'
import axios from 'axios'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
    default: true,
  },
  title: {
    type: Object,
    default: function () {
      return ''
    },
  },
  data: {
    type: Object,
    default: function () {
      return ''
    },
  },
  type: {
    type: Object,
  },
})

const validateIssuingDate = (rule, value, callback) => {
  let data = certificateOfBusinessInfo.value.data
  if (value) {
    if (data.startDate) {
      if (value > data.startDate) {
        callback(new Error('发证日期不能大于营业开始日期'))
      }
    }
    if (data.endDate) {
      if (value > data.endDate) {
        callback(new Error('发证日期不能大于营业截止日期'))
      }
    }
    callback()
  } else {
    callback()
  }
}
const validateStartDate = (rule, value, callback) => {
  let data = certificateOfBusinessInfo.value.data
  if (value) {
    if (data.issuingDate) {
      if (value < data.issuingDate) {
        callback(new Error('营业开始日期不能小于发证日期'))
      }
    }
    if (data.endDate) {
      if (value > data.endDate) {
        callback(new Error('营业开始日期不能大于营业截止日期'))
      }
    }
    callback()
  } else {
    callback()
  }
}
const validateEndDate = (rule, value, callback) => {
  let data = certificateOfBusinessInfo.value.data
  if (value) {
    if (data.issuingDate) {
      if (value < data.issuingDate) {
        callback(new Error('营业截止日期不能小于发证日期'))
      }
    }
    if (data.startDate) {
      if (value < data.startDate) {
        callback(new Error('营业截止日期不能小于营业开始日期'))
      }
    }
    callback()
  } else {
    callback()
  }
}
const validateBIssuingDate = (rule, value, callback) => {
  let data = businessLicenseInfo.value.data
  if (value) {
    if (data.startDate) {
      if (value > data.startDate) {
        callback(new Error('发证日期不能大于许可期限开始日期'))
      }
    }
    if (data.endDate) {
      if (value > data.endDate) {
        callback(new Error('发证日期不能大于许可期限截止日期'))
      }
    }
    callback()
  } else {
    callback()
  }
}
const validateBStartDate = (rule, value, callback) => {
  let data = businessLicenseInfo.value.data
  if (value) {
    if (data.issuingDate) {
      if (value < data.issuingDate) {
        callback(new Error('许可期限开始日期不能小于发证日期'))
      }
    }
    if (data.endDate) {
      if (value > data.endDate) {
        callback(new Error('许可期限开始日期不能大于许可期限截止日期'))
      }
    }
    callback()
  } else {
    callback()
  }
}
const validateBEndDate = (rule, value, callback) => {
  let data = businessLicenseInfo.value.data
  if (value) {
    if (data.issuingDate) {
      if (value < data.issuingDate) {
        callback(new Error('许可期限截止日期不能小于发证日期'))
      }
    }
    if (data.startDate) {
      if (value < data.startDate) {
        callback(new Error('许可期限截止日期不能小于许可期限开始日期'))
      }
    }
    callback()
  } else {
    callback()
  }
}

// 表单相关
const formInfo = ref({
  ref: null,
  data: {},
  fieldList: [
    { label: '机构名称', value: 'name', type: 'input' },
    { label: '地址', value: 'cities', type: 'city-model' },
    { label: '详细地址', value: 'address', type: 'input' },
    { label: '联系电话', value: 'phone', type: 'input' },
  ],
  rules: {
    name: [{ required: true, message: '请填写机构名称', trigger: 'blur' }],
    phone: [{ validator: proxy.$validate.cellphone, trigger: 'blur' }],
  },
  labelWidth: '120px',
})
const certificateOfBusinessInfo = ref({
  ref: null,
  data: {
    issuingDate: '',
    startDate: '',
    endDate: '',
  },
  fieldList: [
    { label: '证书编号', value: 'certificateNumber', type: 'input' },
    { label: '注册地址', value: 'registeredAddress', type: 'input' },
    {
      label: '公司类型',
      value: 'companyType',
      type: 'select-model',
      code: 'company_type',
      checkDefault: false,
    },
    { label: '注册资本(万元)', value: 'registeredCapital', type: 'money' },
    { label: '成立时间', value: 'establishedDate', type: 'date' },
    {
      label: '经营范围',
      value: 'businessScope',
      type: 'textarea',
      isSpecialInput: true,
      maxlength: 200,
    },
    { label: '发证机关', value: 'issuingAuthority', type: 'input' },
    { label: '发证日期', value: 'issuingDate', type: 'date' },
    { label: '营业开始日期', value: 'startDate', type: 'date' },
    { label: '营业截止日期', value: 'endDate', type: 'date' },
    {
      label: '营业执照',
      value: 'licenseFilePath',
      type: 'slot',
      className: 'not-br',
    },
  ],
  labelWidth: '120px',
  rules: {
    issuingDate: [{ validator: validateIssuingDate, trigger: 'change,blur' }],
    startDate: [{ validator: validateStartDate, trigger: 'change,blur' }],
    endDate: [{ validator: validateEndDate, trigger: 'change,blur' }],
    registeredCapital: [
      { validator: proxy.$validate.positiveMoneyNo, target: 'change,blur' },
    ],
    certificateNumber: [
      { validator: proxy.$validate.validatEn, target: 'change,blur' },
    ],
  },
})
const businessLicenseInfo = ref({
  ref: null,
  data: {
    issuingDate: '',
    startDate: '',
    endDate: '',
  },
  fieldList: [
    { label: '证书编号', value: 'certificateNumber', type: 'input' },
    { label: '企业名称', value: 'companyName', type: 'input' },
    { label: '注册地址', value: 'registeredAddress', type: 'input' },
    { label: '法定代表人', value: 'legalRepresentative', type: 'input' },
    { label: '企业负责人', value: 'responsiblePersons', type: 'input' },
    { label: '质量管理人', value: 'qualityManager', type: 'input' },
    {
      label: '经营范围',
      value: 'businessScope',
      type: 'textarea',
      isSpecialInput: true,
      maxlength: 200,
    },
    { label: '发证机关', value: 'issuingAuthority', type: 'input' },
    { label: '发证日期', value: 'issuingDate', type: 'date' },
    { label: '许可期限开始日期', value: 'startDate', type: 'date' },
    { label: '许可期限截止日期', value: 'endDate', type: 'date' },
    {
      label: '经营许可证',
      value: 'licenseFilePath',
      type: 'slot',
      className: 'not-br',
    },
  ],
  labelWidth: '120px',
  rules: {
    issuingDate: [{ validator: validateBIssuingDate, trigger: 'change,blur' }],
    startDate: [{ validator: validateBStartDate, trigger: 'change,blur' }],
    endDate: [{ validator: validateBEndDate, trigger: 'change,blur' }],
    certificateNumber: [
      { validator: proxy.$validate.validatEn, target: 'change,blur' },
    ],
  },
})
const taxPermit = ref({
  ref: null,
  data: {},
  fieldList: [
    { label: '证书编号', value: 'certificateNumber', type: 'input' },
    { label: '法定代表人', value: 'legalRepresentative', type: 'input' },
    { label: '地址', value: 'registeredAddress', type: 'input' },
    {
      label: '登记注册类型',
      value: 'registerType',
      type: 'select-model',
      code: 'company_type',
      checkDefault: false,
    },
    {
      label: '经营范围',
      value: 'businessScope',
      type: 'textarea',
      isSpecialInput: true,
      maxlength: 200,
    },
    { label: '批准设立机关', value: 'approvingAuthority', type: 'input' },
    { label: '发证机关', value: 'issuingAuthority', type: 'input' },
    { label: '发证日期', value: 'issuingDate', type: 'date' },
    {
      label: '税务登记证',
      value: 'licenseFilePath',
      type: 'slot',
      className: 'not-br',
    },
  ],
  rules: {
    certificateNumber: [
      { validator: proxy.$validate.validatEn, target: 'change,blur' },
    ],
  },
  labelWidth: '120px',
})
const businessRecordCertificate = ref({
  ref: null,
  data: {},
  fieldList: [
    { label: '备案编号', value: 'recordNumber', type: 'input' },
    { label: '备案日期', value: 'recordDate', type: 'date' },
    { label: '企业名称', value: 'businessName', type: 'input' },
    { label: '住所', value: 'registeredAddress', type: 'input' },
    { label: '经营场所', value: 'businessAddress', type: 'input' },
    { label: '库房地址', value: 'warehouseAddress', type: 'textarea' },
    { label: '经营方式', value: 'businessType', type: 'input' },
    { label: '法定代表人', value: 'legalRepresentative', type: 'input' },
    { label: '企业负责人', value: 'responsiblePersons', type: 'input' },
    {
      label: '经营范围',
      value: 'businessScope',
      type: 'textarea',
      isSpecialInput: true,
      maxlength: 200,
    },
    { label: '备注', value: 'remark', type: 'input' },
    {
      label: '证书附件',
      value: 'licenseFilePath',
      type: 'slot',
      className: 'not-br',
    },
  ],
  rules: {
    recordNumber: [
      { required: true, message: '请填写备案编号', trigger: 'change,blur' },
    ],
    recordDate: [
      { required: true, message: '请选择备案日期', trigger: 'change,blur' },
    ],
  },
  labelWidth: '120px',
})
const fullInfo = ref({
  btnList: [{ label: '保存', event: save, show: true }],
})
const action = ref(axios.defaults.baseURL + '/pub/uploadfile')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    // 更新父组件visible
    emits('update:visible', val)
  },
})
watch(
  () => props.visible,
  (val) => {
    showDialog.value = val
  }
)
watch(
  () => formInfo.value.data.cities,
  (val) => {
    if (val.length) {
      formInfo.value.data.province = val[0]
      formInfo.value.data.city = val[1]
      formInfo.value.data.county = val[2]
    }
  }
)

function getDetails() {
  getOrgInformation(props.data).then((res) => {
    if (res && res.success) {
      formInfo.value.data = res.data.org || {}
      certificateOfBusinessInfo.value.data = res.data.businessLicense || {}
      businessLicenseInfo.value.data = res.data.businessPermit || {}
      taxPermit.value.data = res.data.taxPermit || {}
      businessRecordCertificate.value.data =
        res.data.businessRecordCertificate || {}
      let { province, city, county } = formInfo.value.data
      let cities = []
      if (province) {
        cities.push(province)
      }
      if (city) {
        cities.push(city)
      }
      if (county) {
        cities.push(county)
      }
      formInfo.value.data['cities'] = cities
    }
  })
}
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      certificateOfBusinessInfo.value.ref.validate((valid1) => {
        if (valid1) {
          businessLicenseInfo.value.ref.validate((valid2) => {
            if (valid2) {
              taxPermit.value.ref.validate((valid3) => {
                if (valid3) {
                  businessRecordCertificate.value.ref.validate((valid4) => {
                    if (valid4) {
                      let api = ''
                      if (props.type === 'update') {
                        api = updateOrgInformation
                      }
                      // formInfo.value.data.id = props.data
                      certificateOfBusinessInfo.value.data.orgId =
                        formInfo.value.data.id
                      certificateOfBusinessInfo.value.data.licenseFilePath =
                        certificateOfBusinessInfo.value.data.licenseFilePaths &&
                        certificateOfBusinessInfo.value.data.licenseFilePaths
                          .length > 0
                          ? certificateOfBusinessInfo.value.data.licenseFilePaths.join(
                              ','
                            )
                          : ''
                      businessLicenseInfo.value.data.orgId =
                        formInfo.value.data.id
                      businessLicenseInfo.value.data.licenseFilePath =
                        businessLicenseInfo.value.data.licenseFilePaths &&
                        businessLicenseInfo.value.data.licenseFilePaths.length >
                          0
                          ? businessLicenseInfo.value.data.licenseFilePaths.join(
                              ','
                            )
                          : ''
                      taxPermit.value.data.orgId = formInfo.value.data.id
                      taxPermit.value.data.licenseFilePath =
                        taxPermit.value.data.licenseFilePathList &&
                        taxPermit.value.data.licenseFilePathList.length > 0
                          ? taxPermit.value.data.licenseFilePathList.join(',')
                          : ''
                      businessRecordCertificate.value.data.orgId =
                        formInfo.value.data.id
                      businessRecordCertificate.value.data.licenseFilePath =
                        businessRecordCertificate.value.data.licenseFilePaths &&
                        businessRecordCertificate.value.data.licenseFilePaths
                          .length > 0
                          ? businessRecordCertificate.value.data.licenseFilePaths.join(
                              ','
                            )
                          : ''
                      let data = {
                        org: formInfo.value.data,
                        businessLicense: certificateOfBusinessInfo.value.data,
                        businessPermit: businessLicenseInfo.value.data,
                        taxPermit: taxPermit.value.data,
                        businessRecordCertificate:
                          businessRecordCertificate.value.data,
                      }
                      api(data).then((res) => {
                        if (res) {
                          emits('callback', true)
                          showDialog.value = false
                        }
                      })
                    }
                  })
                }
              })
            }
          })
        }
      })
    }
  })
}
function handleResponse(response) {
  return response
}

onMounted(() => {
  if (props.data) {
    getDetails()
  }
})
</script>

<style scoped></style>
